#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "AppDaemon.h"
#import "main.h"

CGImageRef CreateCGImageFromFile(NSString* path)
{
    NSURL*            url = [NSURL fileURLWithPath:path];
    CGImageRef        imageRef = NULL;
    CGImageSourceRef  sourceRef;

    sourceRef = CGImageSourceCreateWithURL((CFURLRef)url, NULL);
    if(sourceRef) {
        imageRef = CGImageSourceCreateImageAtIndex(sourceRef, 0, NULL);
        CFRelease(sourceRef);
    }

    return imageRef;
}

@implementation AppDaemon


- (NSString *)executeCommand:(NSString *)cmd
{
    NSString *output = [NSString string];
    FILE *pipe = popen([cmd cStringUsingEncoding: NSASCIIStringEncoding], "r");
    if (!pipe) return nil;

    char buf[1024];
    while(fgets(buf, 1024, pipe)) {
        output = [output stringByAppendingFormat: @"%s", buf];
    }
    pclose(pipe);
    return output;
}

- (void) fireTimer:(NSTimer*)theTimer {

	//CGImageRef sourceImage = [_window _createCGImageRefRepresentationInFrame: [UIHardware fullScreenApplicationContentRect ]];

	
	NSString *imgpath = @"/tmp/foo_0.png";
    [self _dumpScreenContents:@""]; 
	CGImageRef sourceImage = CreateCGImageFromFile(imgpath);
	
	[_imageView doinitImage:sourceImage andClean:true];

	UIAlertSheet *alert = [[UIAlertSheet alloc] initWithFrame:CGRectMake(0,0,320,480)];
	[alert setTitle:@"Waves"];
    [alert setBodyText:@"(Double-Tap to Stop)"];
	[alert addButtonWithTitle:@"Play"];
	[alert addButtonWithTitle:@"Cancel"];
	[alert addButtonWithTitle:@"Quit"];
	[alert setAlertSheetStyle:0];
	[alert setDelegate: self];
	[alert popupAlertAnimated: YES];

}
- (void) alertSheet:(UIAlertSheet *)alert buttonClicked:(int) button
{
    switch(button){
		case 1: {
			[alert dismissAnimated: YES];
			[_window _setHidden: NO];
			[_imageView startEmulator ];
			[_window setFrame: [ UIHardware fullScreenApplicationContentRect ] ];
			[_imageView setFrame: [ UIHardware fullScreenApplicationContentRect ] ];
			[_window setContentView: _imageView];
			break;
		}
		case 2: {
			[alert dismissAnimated: YES];
			[_window _setHidden: NO];
			break;
		}
		case 3: {
			[alert dismissAnimated: NO];
			NSString *path = [[NSBundle mainBundle] bundlePath];
			NSString *stop = [NSString stringWithFormat: @"/bin/launchctl unload -w %@/com.gnese.wavesdaemons.plist", path];
			[self executeCommand: stop];
			break;
		}
	}
}

- (void)Start {

	[_window StopTimer];
	[NSTimer scheduledTimerWithTimeInterval: 0.1
						target: self
						selector: @selector(fireTimer:)
						userInfo: nil
						repeats: NO];

	[_window _setHidden: YES];
}


- (void)Stop {
	[_imageView stopEmulator];
	[_window Reset];
}


- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
	_imageView = NULL;
	_screenOrientation = 0;
	[UIHardware _setStatusBarHeight:0.0f];
	_window = [[SnapButton alloc] initWithParent:self]; 
	
	struct CGRect rect = [UIHardware fullScreenApplicationContentRect];
	rect.origin.x = rect.origin.y = 0.0f;
	[self setStatusBarMode:2 orientation:0 duration:0 fenceID:0];
	[_window orderFront: self];
	[_window makeKey: self];
	[_window _setHidden: NO];
	_imageView = [[MainView alloc] initWithFrame: rect andParent:self];
	screenSurface = [_window createCoreSurfaceWithFrame: CGRectMake(0.0f, 0.0f, 320.0f, 480.0f)];
}




- (void)applicationWillTerminate {
	[_window StopTimer];
	[_window release];
}

- (void) applicationWillSuspend
{
}
- (void) willSleep {
}

- (void) didWake {
}
@end
